package day14;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client2 {
    static volatile boolean isEsc;   //false 没有退出
    public static void main(String[] args) throws IOException {
        Socket client = new Socket("192.168.9.11", 9999);
        OutputStream os = client.getOutputStream();//写的数据来源
        Scanner sc = new Scanner(System.in);    //读取控制台的数据

        //缺少向服务端读取数据
        //由于读写 和 监听服务器的数据 是相互独立的  所以它也是一个线程来实现
        new ClientThread2(client).start();

        System.out.println("请输入你的姓名:");
        String name = sc.nextLine();
        while (true) {
            System.out.println("请输入要发送的信息, esc退出聊天室");
            String msg = sc.nextLine();
            if (msg != null) {
                if (msg.contains("esc")) {
                    os.write((name + "说: 退出聊天室esc\n").getBytes());
                    isEsc = true;   //标记要退出
                    break;
                } else {
                    os.write((name + "说: " + msg + "\n").getBytes());
                }
            }
        }
        os.close();
        client.close();
    }
}
class ClientThread2 extends Thread{
    Socket client;
    public ClientThread2(Socket client){
        this.client = client;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (!Client2.isEsc){
                String msg = br.readLine();
                if (msg!=null){
                    System.out.println(msg);
                }
            }
        } catch (Exception e) {}
    }
}